/**
 * 埋点追踪模块
 */

'use strict'

const Service = require('egg').Service

class TrackingService extends Service {
  async getTrackingList(queryInfo) {
    // 如果没有 queryInfo.pagenum，说明是获取全部（这个不要做默认值修改，因为其他模块会调用该接口获得所有部门数据）
    if (!queryInfo.pageNum) {
      let resultAll = await this.app.mysql.query(
        'SELECT * FROM event_tracking order by create_time desc'
      )

      return this.ctx.getRESTfulData(
        {
          total: resultAll.length,
          trackingList: resultAll,
        },
        '获取成功',
        200
      )
    }

    // 时间区间搜索
    let dateBetween = `and create_time >= ${queryInfo.startTime} and create_time <= ${queryInfo.endTime}`
    if (queryInfo.startTime === '0' || queryInfo.endTime === '0') {
      dateBetween = ''
    }

    let resultAll = await this.app.mysql.query(
      `SELECT 
      *
      FROM event_tracking 
      WHERE type like ? and ip_address like ? ${dateBetween}`,
      ['%' + queryInfo.type + '%', '%' + queryInfo.ip_address + '%']
    )

    let result = await this.app.mysql.query(
      `SELECT 
      *
      FROM event_tracking 
      WHERE type like ? and ip_address like ? ${dateBetween}
      LIMIT ?,?`,
      [
        '%' + queryInfo.type + '%',
        '%' + queryInfo.ip_address + '%',
        parseInt(queryInfo.pageNum - 1) * queryInfo.pageSize,
        parseInt(queryInfo.pageSize),
      ]
    )

    return this.ctx.getRESTfulData(
      {
        total: resultAll.length,
        trackingList: result,
      },
      '获取筛选列表成功',
      200
    )
  }

  async createTracking(trackingInfo) {
    const result = await this.app.mysql.insert('event_tracking', {
      ...trackingInfo,
    })

    return this.ctx.getRESTfulData(null, '添加成功', 201)
  }

  async deleteTracking(id) {
    let result = await this.app.mysql.delete('event_tracking', {
      id,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '删除成功',
          status: 200,
        },
      }
    }
  }
}

module.exports = TrackingService
